import axios from 'axios'
import {Message} from 'element-ui'
import store from '@/store'
import router from '@/router'
// 创建axios实例
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    timeout: 10000
})

// 请求拦截器
service.interceptors.request.use(
    config => {
        console.log(32323)
        if (store.getters.token) {
            config.headers['token'] = `${store.getters.token}`
        }
        return config
    },
    error => {
        console.log(error)
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    response => {
        const res = response.data

        // 业务状态码判断
        if (res.code !== 200) {
            console.log(21212)
            if (res.code === 10000) {
                localStorage.setItem('token', null)
                // 登出逻辑
                router.push('/login')
            } else if (res.code !== 40000) {
                Message.error('系统错误，请联系技术人员' || 'Error')
            } else {
                Message.error(res.msg || 'Error')
            }


            // 特殊状态码处理
            if (res.code === 401) {
                store.dispatch('user/resetToken').then(() => {
                    location.reload()
                })
            }
            return res
        } else {
            return res
        }
    },
    error => {
        Message.error(error.message || 'Network Error')
        return Promise.reject(error)
    }
)

// 封装通用请求方法
export function get(url, params) {
    return service({
        url,
        method: 'get',
        params
    })
}

export function post(url, data) {
    return service({
        url,
        method: 'post',
        data
    })
}

export function del(url, params) {
    return service({
        url,
        method: 'delete',
        params
    })
}

export function put(url, data) {
    return service({
        url,
        method: 'put',
        data
    })
}

export default service
